import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json
import pandas as pd
from sqlalchemy import create_engine, text

# 选出报告期为2025-06-30，净利润同比增长 ≥ 10%，净利润（本期） > 10亿

# ================= MySQL 连接配置 =================
engine = create_engine('mysql+pymysql://root:123456@localhost:3306/cn_stock_data')

# ================= 钉钉机器人配置 =================
access_token = "16bb331727340eaea9ab212c0d0ddb5148f60456b4cc9e6a02c35578796c20b3"
secret = "SEC3758a8faa7e911b364aa8217ea59e350022a007f11c6a217d2bd118a4f9dd52a"

def send_dingtalk_message(content: str, chunk_size: int = 4000):
    """分批发送钉钉消息，避免超出限制"""
    chunks = [content[i:i+chunk_size] for i in range(0, len(content), chunk_size)]
    for idx, chunk in enumerate(chunks, start=1):
        timestamp = str(round(time.time() * 1000))
        string_to_sign = f'{timestamp}\n{secret}'
        hmac_code = hmac.new(secret.encode('utf-8'),
                             string_to_sign.encode('utf-8'),
                             hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

        webhook_url = f"https://oapi.dingtalk.com/robot/send?access_token={access_token}&timestamp={timestamp}&sign={sign}"
        headers = {"Content-Type": "application/json"}
        data = {"msgtype": "text", "text": {"content": chunk}}
        response = requests.post(webhook_url, headers=headers, data=json.dumps(data))
        print(f"📤 发送第 {idx}/{len(chunks)} 条消息, 状态码: {response.status_code}")
        time.sleep(0.5)

def main():
    # ================= 设置目标报告期 =================
    target_report_date = "2025-06-30"
    
    with engine.begin() as conn:
        df = pd.read_sql(text("""
            SELECT
                ps.stock_code,
                ps.stock_name,
                ps.net_profit AS net_profit_this_year,
                ps.report_date AS report_date_this_year,
                ly.net_profit AS net_profit_last_year,
                ly.report_date AS report_date_last_year
            FROM profit_statement ps
            LEFT JOIN profit_statement ly
                ON ps.stock_code = ly.stock_code
                AND ly.report_date = DATE_SUB(ps.report_date, INTERVAL 1 YEAR)
            WHERE ps.report_date = :target_report_date
        """), conn, params={"target_report_date": target_report_date})
    
    if df.empty:
        print(f"⚠️ 报告期 {target_report_date} 没有数据")
        return
    
    df["growth_rate"] = (df["net_profit_this_year"] - df["net_profit_last_year"]) / df["net_profit_last_year"]
    
    result = df[
        (df["growth_rate"] >= 0.20) &
        (df["net_profit_last_year"].notnull()) &
        (df["net_profit_this_year"] > 1e9)
    ]
    
    if result.empty:
        print(f"✅ 报告期 {target_report_date} 没有净利润增长 ≥10% 且净利润 > 10亿的公司")
        return
    
    msg_lines = [f"📈 报告期 {target_report_date} 净利润同比增长 ≥10% 且净利润 > 10亿的公司："]
    for _, row in result.iterrows():
        msg_lines.append(
            f"{row['stock_code']} {row['stock_name']} | "
            f"净利润: {row['net_profit_this_year']:.2f} ({row['report_date_this_year']}) | "
            f"去年同期: {row['net_profit_last_year']:.2f} ({row['report_date_last_year']}) | "
            f"同比: {row['growth_rate']*100:.2f}%"
        )
    
    send_dingtalk_message("\n".join(msg_lines))

if __name__ == "__main__":
    main()
